<?php

namespace App\Http\Controllers\Api;

use app\admin\model\Admin;
use App\Models\AdminUsers;
use App\Models\AgricGoods;
use App\Models\Article;
use App\Models\ArticleOperateLog;
use App\Models\IntegralRecord;
use App\Models\IntegralRule;
use App\Models\Sms;
use App\Models\SystemRegion;
use App\Models\User;
use App\Models\UserAddress;
use App\Models\UserCollect;
use App\Models\UserFollow;
use App\Models\UserRelations;
use App\Models\Video;
use App\Models\VillageThings;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Tymon\JWTAuth\Facades\JWTAuth;

class UserController extends Controller
{
    public $user_id = '';

    public function __construct()
    {
        $this -> user_id = auth() -> id();
    }

    public function index(){

        $user = User::find($this -> user_id);

        if($user){
            return jsonSuccess($user);
        }else{
            return jsonError();
        }

    }

    /**
     * 用户注册
     */
    public function register(Request $request)
    {
        $credentials = [
            'phone_num' => $request->phone_num,
            'user_pwd' => $request->user_pwd,
            'captcha' => $request -> captcha,
            'user_name' => str_replace(substr($request->phone_num,3,4),'****',$request -> phone_num)
        ];


        $message = [
            'phone_num.required' => '请输入手机号',
            'user_pwd.required'  => '请输入密码',
            'max'                => '请输入长度小于:max的密码',
            'user_pwd.regex'     => '请输入数字、字母的密码',
            'phone_num.regex'    => '请输入正确的手机号',
            'captcha.required'   => '请输入验证码',
            'captcha.regex'      => '请输入4位数字的验证码',
        ];

        //规则验证
        $validator = Validator::make($credentials,[
            'phone_num' => ['required','regex:/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/'],
            'user_pwd'  => ['required','max:30','regex:/^[a-zA-Z0-9]+$/'],
            'captcha'   => ['required','regex:/^[0-9]{4}$/'],
        ],$message);

        // 判断手机号是否已注册
        if(User::where('phone_num',$request -> phone_num) -> first()){
            return jsonError(4012);
        }

        // 验证失败返回
        if($validator -> fails()){
            return jsonError($validator -> messages()-> first());
        }

        // 判断验证码是否正确
        if(!Sms::check($request -> captcha,$request -> phone_num,'REGISTER')){
            return jsonError(4003);
        }

        $credentials['user_pwd'] = Hash::make($request->user_pwd);

        $user = User::create($credentials);
        if($user){
            $token = JWTAuth::fromUser($user); // 生成token
            return jsonSuccess($this->responseWithToken($token));
        }else{
            return jsonError(4015);
        }
    }

    //登陆
    public function login(Request $request)
    {
        $arr  = $request -> toArray();

        $message = [
            'phone_num.required' => '请输入手机号',
            'phone_num.regex'    => '请输入正确的手机号',
            'captcha.required'   => '请输入验证码',
            'captcha.regex'      => '请输入4位数字的验证码',
            //'user_pwd.required'  => '密码不能为空',
        ];
        $validator = Validator::make($arr,[
            'phone_num' => ['required','regex:/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/'],
            //'user_pwd'  => 'required',
            'captcha'   => ['required','regex:/^[0-9]{4}$/'],
        ],$message);
        //返回验证错误
        if($validator -> fails()){
            return jsonError($validator -> messages()-> first());
        }

        // 判断验证码是否正确
        if(!Sms::check($request -> captcha,$request -> phone_num,'LOGIN')){
            return jsonError(4003);
        }

        $user = User::where('phone_num',$arr['phone_num']) -> first();
        if(!is_null($user)){

            $user -> last_login_time = date('Y-m-d H:i:s',time());
            $user -> save();

            $token = JWTAuth::fromUser($user); // 生成token

            return jsonSuccess($this->responseWithToken($token));
        }else{

            $userData = [
                'user_name' => str_replace(substr($arr['phone_num'],3,4),'****',$arr['phone_num']),
                'phone_num' => $arr['phone_num'],
                'last_login_time' => date('Y-m-d H:i:s',time()),
                'head_portrait' => 'default/headpic.png',
            ];

            $user = User::create($userData);
            if($user){
                // 注册成功，添加积分
                IntegralRule::rule(1,$user -> id);
                $token = JWTAuth::fromUser($user); // 生成token
                return jsonSuccess($this->responseWithToken($token));
            }else{
                return jsonError(4013);
            }
        }
    }

    //手机验证码登陆
    public function mbLogin(request $request){

        $arr = $request -> toArray();
        $message = [
            'phone_num.required'  => '请输入手机号',
            'phone_num.regex'     => '请输入正确的手机号',
            'captcha.required'    => '请输入验证码',
            'captcha.regex'       => '请输入4位数字的验证码',
        ];
        $validator = Validator::make($arr,[
            'phone_num' => ['required','regex:/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/'],
            'captcha' => ['required','regex:/^[0-9]{4}$/'],
        ],$message);

        // 验证失败返回
        if($validator -> fails()){
            return jsonError($validator -> messages()-> first());
        }

        //判断用户是否存在
        if($user = User::where('phone_num',$request -> phone_num) -> first()){

            //判断验证码是否正确
            if(!Sms::check($request -> captcha,$request -> phone_num,'LOGIN')){
                return jsonError(4003);
            }

            $token = JWTAuth::fromUser($user);
            return jsonSuccess($this -> responseWithToken($token));
        }else{
            return jsonError(4002);
        }

    }

    /**
     * 根据token获得用户信息
     * @param Request $request
     * @return int|null
     */
    public function getUser(Request $request)
    {
        if($request -> has('user_id')){
            $user_id = $request -> input('user_id');
            $user = User::find($user_id);
        }else{
            $user_id = auth() ->id();
            $user = auth() -> user();
        }
        $user_address = UserAddress::where('user_id',$user_id) -> select('id','prov','city','country','town') -> first();
        $user -> head_portrait_url = config('app.img_url') . $user -> head_portrait;
        $user -> region_id = $user -> region_code ? (SystemRegion::where('region_code',$user -> region_code) -> value('id') ?: 0) : 0;

        if($user_address){
            $newArr = [];

            $newArr[] = User::getAddress($user_address['prov']);
            $newArr[] = User::getAddress($user_address['city']);
            $newArr[] = User::getAddress($user_address['country']);
            $newArr[] = User::getAddress($user_address['town']);

            $user -> user_address = collect($newArr);
        }else{
            $user -> user_address = null;
        }



        return jsonSuccess($user); // 登录用户的ID
    }

    /**
     * @param Request $request
     * @return string
     */
    public function forgetPwd(Request $request)
    {
        $requestArr = $request -> toArray();
        $message = [
            'phone_num.required' => '请输入手机号',
            'phone_num.regex'    => '请输入正确的手机号',
            'user_pwd.required'  => '请输入密码',
            'user_pwd.confirmed' => '两次输入密码不一致',
            'captcha.required'   => '请输入验证码',
            'captcha.regex'      => '请输入4位数字的验证码',
        ];
        $validator = Validator::make($requestArr,[
            'phone_num' => ['required','regex:/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/'],
            'user_pwd' => 'required|confirmed',
            'captcha' => ['required','regex:/^[0-9]{4}$/'],
        ],$message);

        // 验证失败返回
        if($validator -> fails()){
            return jsonError($validator -> messages()-> first());
        }

        // 判断验证码是否正确
        if(!Sms::check($request -> captcha,$request -> phone_num,'FORGET_PWD')){
            return jsonError(4003);
        }

        $user = new User();
        if($user = $user -> where('phone_num',$request -> phone_num) -> first()){

            $user -> user_pwd = Hash::make($request -> user_pwd);
            $res = $user -> save();
            if($res){

                return jsonSuccess();
            }else{
                return jsonError(4001);
            }
        }else{
            return jsonError(4002);
        }

    }

    /**
     * 刷新token
     */
//    public function refresh()
//    {
//        return jsonSuccess($this->responseWithToken(auth()->refresh()));
//    }

    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        auth()->logout();
    }

    /**
     * 响应
     */
    private function responseWithToken(string $token)
    {
        $response = [
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ];
        return $response;
    }


    // 个人信息提交
    public function userInfo(Request $request){

        if(!check_id_num($request -> input('id_num'))){
            return jsonError(4009);
        }

        if(!$request ->input('real_name')){
            return jsonError(4030);
        }

        if(!$request -> has('address_region')){
            return jsonError(4000);
        }
        $address_region = json_decode($request -> address_region,true);


        $userDetailAddress = User::userDetailAddress($request -> all());

        $param = [
            'user_id' => $this -> user_id,
            'address_region' => $address_region
        ];
        if($address_region){
            $userAddress = UserAddress::userAddressStore($param);
        }

        if($userDetailAddress){
            // 完善资料，送积分
            IntegralRule::rule(3,$this -> user_id);
            return jsonSuccess(2007);
        }else{
            return jsonError( 4018);
        }
    }


    // 关注或取消关注 文章用户
    public function followOrCancel(Request $request)
    {

        if($request -> post()){
            if($request -> filled('user_id')){
                $user_id           = auth() -> id();
                $followed_user_id  = $request -> input('user_id');
                $is_admin          = $request -> input('is_admin');


                $userFollow = UserFollow::followOrCancel($user_id,$followed_user_id,$is_admin);
                if($userFollow){
                    return jsonSuccess();
                }else{
                    return jsonError();
                }
            }else{
                return jsonError(4020);
            }
        }

    }

    // 我的关注
    public function myFollows(Request $request){

        $userfollow = UserFollow::where('user_id',$this -> user_id) -> get();

        foreach($userfollow as $v){

            if($v -> is_admin){

                $v -> followed_user = AdminUsers::select('id','name','avatar') -> find($v -> follow_admin_id);
            }else{

                $v -> followed_user = User::select('id','user_name as name','head_portrait as avatar') -> find($v -> follow_user_id);
                $v -> followed_user -> avatar_url = config('app.img_url') . $v -> followed_user -> avatar;
            }

        }
        return jsonSuccess($userfollow);
    }

    //  个人主页--被关注者的用户信息
    public function userinfoFollowed(Request $request)
    {
        if($request -> filled('user_id')){


            if($request -> input('is_admin')){
                $res = UserFollow::adminUserInfo($request -> input('user_id'));
            }else{
                $res = UserFollow::userInfo($request -> input('user_id'));
            }

            return jsonSuccess($res);
        }else{
            return jsonError(4020);
        }
    }


    // 我的喜欢 和 收藏
    public function myCollects(Request $request){

        $pagesize = $request -> input('pagesize') ?: '3';
        $types    = $request -> input('types');
        $user_id  = auth() -> id();

        $message = [
            'types.required' => '请输入文章类型'
        ];
        $validator = Validator::make($request->all(),[
            'types' => 'required'
        ],$message);
        if($validator -> fails()){
            return jsonError($validator -> messages()-> first());
        }


        $myCollectsArticle = UserCollect::with(['article:id,article_title,user_id,admin_id,content,list_img,imgs,is_show,created_at,updated_at'])
            -> select('id','user_id','obj_id','obj_types','types')
            -> where('obj_types',1)
            -> where('user_id',$user_id)
//            -> where('article.is_show',1)
            -> where('types',$types)
            -> paginate($pagesize);


        return jsonSuccess($myCollectsArticle);
    }

    // 我的喜欢 和 收藏 删除
    public function myCollectsDel(Request $request){

        $ids = $request -> input('ids');
        if($ids){
            $ids = explode(',',$ids);
            DB::beginTransaction();

            try{

                foreach($ids as $v){
                    $userCollect = UserCollect::find($v);

                    $article = Article::find($userCollect->obj_id);

                    if($userCollect -> types == 1){
                        $res1 = $article -> decrement('like_num');
                    }else{
                        $res1 = $article -> decrement('collect_num');
                    }


                    $log = [
                        'article_id' => $userCollect->obj_id,
                        'operate_type' => ($userCollect -> types==1 ? 3 : 4),
                        'user_id' => $userCollect -> user_id
                    ];

                    if($logs = ArticleOperateLog::where($log) -> first()){
                        $res2 = $logs -> delete();
                    }else{ $res2 = 0;}

                    $res3 = $userCollect -> delete();
                }

                if($res1 && $res2 && $res3){
                    DB::commit();
                    return jsonSuccess();
                }else{

                    DB::rollback();
                    return jsonError(4010);
                }
            }catch(\Exception $e){
                DB::rollback();
                return jsonError(4010);
            }

        }else{
            return jsonError(4011);
        }

    }



    /**
     * 获得地区信息
     * @param Request $request
     * @return false|string
     */
    public function addressNew(Request $request)
    {
        $parents_code = $request->input('code') == 0 ? '' : $request->input('code'); // 父级code，为空时获得全部省

        $addressInfo = User::getAddressByPrentsCode($parents_code);
        return jsonSuccess($addressInfo);
    }

    /*通过经纬度获取地址信息*/
    public function lngLat(Request $request)
    {
        $lng = $request -> filled('lng') ? ($request -> input('lng')) : false;
        $lat = $request -> filled('lat') ? ($request -> input('lat')) : false;
        if(!$lng || !$lat){
            return jsonError(4011);
        }

        $res = User::getLocal($lng, $lat);
        if($res['info'] == 'OK'){
            $result = $res['regeocode']['addressComponent'];
            /*$data = [
                'city' => $result['city'],
                'province' => $result['province'],
                'district' => $result['district'],
                'township' => $result['township'],
                'towncode' => $result['towncode']
            ];*/


            $system_region = SystemRegion::where('region_code',$result['towncode']) -> get(['id','region_name','region_code','status']);


            if(!$system_region -> first()){
                $system_region = ['id' => 0, 'region_name' => $result['township']];
            }else{
                $system_region = $system_region -> first();
            }

            return jsonSuccess($system_region);
        }else{
            return jsonError(4025);
        }
    }


    /*
     * 返回邀请码
     * @return array
     */
    public function getInviteCode()
    {
        $user_id = auth() -> id();
        $invite_code = UserRelations::store($user_id);
        $invite_code -> invite_qrcode = $invite_code -> invite_qrcode ?: (config('app.url').'/img/download_qrcode.png');

        unset($invite_code -> created_at, $invite_code -> updated_at, $invite_code -> deleted_at);
        $invite_code -> total_invite_integral    = IntegralRecord::where('user_id',$user_id) -> where('obj_source',10) -> sum('integral_num');
        $invite_code -> standard_invite_integral = IntegralRule::find(10) -> integral;

        return jsonSuccess($invite_code);
    }


    /*
     * 邀请码回填
     * @return bool
     */
    public function backInviteCode(Request $request)
    {
        $invite_code = $request -> input('invite_code');
        if(!$request -> filled('invite_code')){
            return jsonError(4020);
        }

        // 判断是否是自己邀请自己
        $user_id = auth() -> id();
        $userRelationId = UserRelations::where('invite_code',$invite_code) -> value('user_id');
        if($userRelationId == $user_id){
            return jsonError(4034);
        }


        $storeInviter = UserRelations::storeInviter($invite_code);

        if($storeInviter){
            if($storeInviter['error']){
                return jsonError($storeInviter['error']);
            }

            // 邀请好友，送积分
            $integralRule = IntegralRule::rule(10,$userRelationId);
            return jsonSuccess(($integralRule ?: []),'',200,2007);
        }else{
            return jsonError(4033);
        }

    }


    /*
     * 用户积分记录表
     * @return array
     */
    public function integralRecords(Request $request)
    {
        $pagesize      = $request -> input('pagesize') ?? 5;
        $obj_source    = $request -> input('obj_source');
        $created_at    = $request -> input('created_at');
        $types    = $request -> input('types');
        $user_id  = auth() -> id();


        $IntegralRecord = IntegralRecord::where('user_id',$user_id)

            -> where(function ($query) use($types,$obj_source){
             if($types){
                 $query -> where('types',$types);
             }
             if($obj_source){
                 $query -> where('obj_source', $obj_source);
             }

         });

        if($created_at){
            $start = date('Y-m-01',strtotime($created_at));
            $end   = date('Y-m-t',strtotime($created_at));

            $IntegralRecord -> whereBetween('created_at',[$start,$end]);
        }
        $res = $IntegralRecord -> orderBy('id','desc') -> paginate($pagesize);

        foreach($res as $v){
            if($v -> obj_source == 1){
                $v -> img = config('app.url').'/img/app/gold_icon.png';
            }else if($v -> obj_source == 2){
                $goods_img = AgricGoods::where('id',$v -> obj_id) -> value('goods_img');
                $v -> img = config('app.img_url').$goods_img;
            }

            $v -> created_at_new = $v -> created_at -> format('m-d');
        }

        return jsonSuccess($res);
    }

    /**
     * @param Request $request
     */
    public function integralRule(Request $request)
    {

        $integralRule = IntegralRule::where('app_show',1) -> orderBy('id') -> get(['id','remark','app_title','app_icon','app_show']);

        foreach($integralRule as $integralRuleVal){

            $integralRuleVal -> app_icon_url = config('app.img_url') . $integralRuleVal -> app_icon;
        }

        return jsonSuccess($integralRule);

    }


    /*
     * 将积分记录录入到记录表中
     * @return bool
     */
    public function integralOperate(Request $request)
    {
        $obj_id  = $request -> input('obj_id') ?? 0;
        $rule_id = $request -> input('rule_id');
        $types   = $request -> input('types') ?? 1;
        $user_id = auth() -> id();
        if (!$user_id) {
            return jsonError('未登录', 4002, 402);
        }

        if($rule_id){


            $res = IntegralRule::rule($rule_id,$user_id,$obj_id,$types);

            if($res){
                return jsonSuccess([],$res['msg']);
            }else{
                return jsonSuccess();
            }
        }else{
            return jsonError();
        }
    }


    /**
     * 设置头像
     */
    public function avatarSet(Request $request){
        $user_id = auth() -> id();
        $avatar = $request -> input('avatar');
        if(!$avatar){
            return jsonError();
        }

        $user = User::find($user_id);
        $user -> head_portrait = $avatar;
        $res = $user -> save();
        return jsonSuccess(2007);
    }
}
